package com.example.chongwushangcheng;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.petshopping.R;
import com.example.chongwushangcheng.adapter.CarouselAdapter;
import com.example.chongwushangcheng.adapter.CommentAdapter;
import com.example.chongwushangcheng.model.Comment;
import com.example.chongwushangcheng.model.Reply;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

public class PetExchangeDetailActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private LinearLayout indicatorsContainer;
    private Button btnFollow;
    private Button btnSend;
    private EditText etComment;
    private RecyclerView rvComments;
    private TextView tvProfileName;
    private CircleImageView ivProfileAvatar;

    private List<Integer> carouselImages;
    private List<View> indicators;
    private List<Comment> commentList;
    private CommentAdapter commentAdapter;
    
    private String replyUsername = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pet_exchange_detail);

        // 初始化视图
        initViews();
        
        // 设置轮播图
        setupCarousel();
        
        // 设置评论列表
        setupComments();
        
        // 设置点击事件
        setupClickListeners();
    }

    private void initViews() {
        viewPager = findViewById(R.id.viewPager);
        indicatorsContainer = findViewById(R.id.indicatorsContainer);
        btnFollow = findViewById(R.id.btn_follow);
        btnSend = findViewById(R.id.btn_send);
        etComment = findViewById(R.id.et_comment);
        rvComments = findViewById(R.id.rv_comments);
        tvProfileName = findViewById(R.id.tv_profile_name);
        ivProfileAvatar = findViewById(R.id.iv_profile_avatar);
        
        // 返回按钮
        ImageButton btnBack = findViewById(R.id.btn_back);
        btnBack.setOnClickListener(v -> finish());
    }

    private void setupCarousel() {
        // 轮播图数据
        carouselImages = Arrays.asList(
            R.drawable.yugang,
            R.drawable.pet_2,
            R.drawable.pet_2,
            R.drawable.pet_2,
            R.drawable.pet_2
        );
        
        // 设置轮播图适配器
        CarouselAdapter carouselAdapter = new CarouselAdapter(this, carouselImages, true);
        viewPager.setAdapter(carouselAdapter);
        
        // 添加指示器
        indicators = new ArrayList<>();
        for (int i = 0; i < carouselImages.size(); i++) {
            View indicator = new View(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    getResources().getDimensionPixelSize(R.dimen.indicator_width),
                    getResources().getDimensionPixelSize(R.dimen.indicator_height)
            );
            layoutParams.setMargins(
                    getResources().getDimensionPixelSize(R.dimen.indicator_margin),
                    0,
                    getResources().getDimensionPixelSize(R.dimen.indicator_margin),
                    0
            );
            indicator.setLayoutParams(layoutParams);
            indicator.setBackgroundResource(R.drawable.indicator_inactive);
            indicatorsContainer.addView(indicator);
            indicators.add(indicator);
        }
        
        // 设置当前指示器
        setCurrentIndicator(0);
        
        // 设置页面切换监听
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                setCurrentIndicator(position);
            }
        });
        
        // 自动轮播
        final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            int currentPage = 0;
            
            @Override
            public void run() {
                if (currentPage == carouselImages.size()) {
                    currentPage = 0;
                }
                viewPager.setCurrentItem(currentPage++, true);
                handler.postDelayed(this, 3000);
            }
        };
        
        handler.postDelayed(runnable, 3000);
    }
    
    private void setCurrentIndicator(int position) {
        for (int i = 0; i < indicators.size(); i++) {
            if (i == position) {
                indicators.get(i).setBackgroundResource(R.drawable.indicator_active);
            } else {
                indicators.get(i).setBackgroundResource(R.drawable.indicator_inactive);
            }
        }
    }
    
    private void setupComments() {
        // 评论数据
        commentList = new ArrayList<>();
        
        // 添加评论
        Comment comment1 = new Comment(1, R.drawable.pet_2, "用户昵称", 
                "评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论。", "2025-07-05", false);
        
        Comment comment2 = new Comment(2, R.drawable.pet_2, "用户昵称", 
                "评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论。", "2025-07-05", false);
        
        Reply reply = new Reply(1, R.drawable.pet_2, "Li", 
                "评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论。", "2025-07-05 23:42:23", true);
        comment2.addReply(reply);
        
        Comment comment3 = new Comment(3, R.drawable.pet_2, "用户昵称", 
                "评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论评论。", "2025-07-05", false);
        
        commentList.add(comment1);
        commentList.add(comment2);
        commentList.add(comment3);
        
        // 设置评论适配器
        commentAdapter = new CommentAdapter(this, commentList);
        rvComments.setLayoutManager(new LinearLayoutManager(this));
        rvComments.setAdapter(commentAdapter);
        
        // 设置回复点击监听器
        commentAdapter.setOnReplyClickListener((position, comment) -> {
            replyUsername = comment.getUsername();
            etComment.setText("回复 " + replyUsername + "：");
            etComment.setSelection(etComment.getText().length());
            etComment.requestFocus();
            // 显示软键盘
            Utils.showKeyboard(this, etComment);
        });
    }
    
    private void setupClickListeners() {
        // 关注按钮点击事件
        btnFollow.setOnClickListener(v -> {
            if ("关注".equals(btnFollow.getText().toString())) {
                btnFollow.setText("已关注");
                btnFollow.setBackgroundResource(R.drawable.bg_button_followed);
            } else {
                btnFollow.setText("关注");
                btnFollow.setBackgroundResource(R.drawable.bg_button_follow);
            }
        });
        
        // 发送按钮点击事件
        btnSend.setOnClickListener(v -> {
            String content = etComment.getText().toString().trim();
            if (content.isEmpty()) {
                Toast.makeText(this, "评论内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            
            // 获取当前时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String time = sdf.format(new Date());
            
            // 处理回复
            if (replyUsername != null && content.startsWith("回复 " + replyUsername + "：")) {
                // 提取回复内容
                String replyContent = content.substring(("回复 " + replyUsername + "：").length());
                
                // 查找要回复的评论
                for (Comment comment : commentList) {
                    if (comment.getUsername().equals(replyUsername)) {
                        // 添加回复
                        Reply newReply = new Reply(comment.getReplies().size() + 1, R.drawable.pet_2, "Li", 
                                replyContent, time, true);
                        comment.addReply(newReply);
                        break;
                    }
                }
            } else {
                // 添加新评论
                Toast.makeText(this, "评论已发送！", Toast.LENGTH_SHORT).show();
            }
            
            // 更新列表
            commentAdapter.notifyDataSetChanged();
            
            // 清空输入框并重置回复状态
            etComment.setText("");
            replyUsername = null;
            
            // 隐藏软键盘
            Utils.hideKeyboard(this, etComment);
        });
    }

    /**
     * 工具类
     */
    private static class Utils {
        public static void showKeyboard(AppCompatActivity activity, View view) {
            if (view.requestFocus()) {
                android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)
                        activity.getSystemService(INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.showSoftInput(view, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT);
                }
            }
        }
        
        public static void hideKeyboard(AppCompatActivity activity, View view) {
            android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager)
                    activity.getSystemService(INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }
} 